//
//  ZYMessageListVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/2.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYMessageListVC.h"
#import "ZYMessageListViewCell.h"
#import "ZYMessage.h"
#import "ZYNavigationView.h"
#import "ZYMessageDetailVC.h"
#import "ZYMessage.h"
#import "ZYMessageViewModel.h"
#import "UITableView+FDTemplateLayoutCell.h"

#define kMessageCellListItemID @"kMessageCellListItemID"

@interface ZYMessageListVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSArray<ZYMessage *> *userMessageArray;
@property(nonatomic,strong) NSArray<ZYMessage *> *systemMessageArray;
@property(nonatomic,strong) ZYMessageViewModel *viewModel;
@property(nonatomic,assign) BOOL isNewMessage;
@end

@implementation ZYMessageListVC


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_ME_MAIN_MESSAGE_CONTROLLER_TITLE];
    [self.viewModel.isReadCommand execute:nil];
}

#pragma mark -init
-(void)setup{
    [self setupTableView];
    [self bindView];
    [self.viewModel loadSystemMessageList];
    [self.viewModel loadUserMessageList];
}

-(void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H - self.navigationView.height)];
    [self.view addSubview:_tableView];
    [_tableView registerClass:[ZYMessageListViewCell class] forCellReuseIdentifier:kMessageCellListItemID];//ios 9必须写在dataSource赋值前面
    _tableView.top = self.navigationView.bottom;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.backgroundColor = [UIColor whiteColor];
    [_tableView reloadData];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

-(void)bindView{
    @weakify(self);
    [[[self.viewModel.systemMessageCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.systemMessageArray = x;
        for (ZYMessage *message in x) {
            message.messageType = ZYMessageTypeSystem;
        }
        [self.tableView reloadData];
    }];

    [[[self.viewModel.userMessageCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.userMessageArray = x;
        for (ZYMessage *message in x) {
            message.messageType = ZYMessageTypeDevice;
        }
        [self.tableView reloadData];
        [self.viewModel.isReadCommand execute:nil];
    }];
    [self.viewModel.userMessageCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    //判断是否有未读消息
    [[[self.viewModel.isReadCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.isNewMessage = [x boolValue];
        [self.tableView reloadData];
    }];
    [self.viewModel.isReadCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        if([[NSErrorHelper handleErrorMessage:x] isEqualToString:LOGIN_FAILURE]){
            //登录失效
            [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
        }
    }];
}

#pragma mark - Table view data source

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(section == 0 && (!_systemMessageArray || [_systemMessageArray count] == 0)){
        return 0;
    }
    if(section == 1 && (!_userMessageArray || [_userMessageArray count] == 0)){
        return 0;
    }
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView fd_heightForCellWithIdentifier:kMessageCellListItemID cacheByIndexPath:indexPath configuration:^(ZYMessageListViewCell *  cell) {
        cell.fd_enforceFrameLayout = NO;
        ZYMessage *message;
        if(indexPath.section == 0){
            message = [self.systemMessageArray objectAtIndex:0];
        }else{
            message = [self.userMessageArray objectAtIndex:0];
        }
        cell.message = message;
    }];
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYMessageListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kMessageCellListItemID];
    // 判断为空进行初始化  --（当拉动页面显示超过主页面内容的时候就会重用之前的cell，而不会再次初始化）
    if (!cell) {
        cell = [[ZYMessageListViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kMessageCellListItemID];
    }
    ZYMessage *message;
    if(indexPath.section == 0){
        message = [self.systemMessageArray objectAtIndex:0];
    }else{
        message = [self.userMessageArray objectAtIndex:0];
    }
    cell.message = message;
    if(indexPath.section != 0 && _isNewMessage){
        cell.isNewMessage = YES;
    }else{
        cell.isNewMessage = NO;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZYMessageDetailVC *vc = [[ZYMessageDetailVC alloc] init];
    ZYMessage *message;
    if(indexPath.section == 0){
        message = [self.systemMessageArray objectAtIndex:0];
    }else{
        message = [self.userMessageArray objectAtIndex:0];
    }
    vc.messageType = message.messageType;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -Getter

-(ZYMessageViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYMessageViewModel alloc] init];
    }
    return _viewModel;
}
@end
